/*
 * ConfigForm.java
 *
 * Created on 2.05.2005, 18:19
 *
 * Copyright (c) 2005-2007, Eugene Stahov (evgs), http://bombus-im.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * You can also redistribute and/or modify this program under the
 * terms of the Psi License, specified in the accompanied COPYING
 * file, as published by the Psi Project; either dated January 1st,
 * 2005, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package Client;
import com.alsutton.jabber.datablocks.Presence;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.lcdui.*;
import locale.SR;
import ui.controls.NumberField;
import util.StringLoader;
import ui.*;

/**
 *
 * @author Evg_S
 */

/*
 * roster elements:
 *  [] self-contact
 *  [] offline contacts
 *  [] transports
 *  [] hidden group
 *  [] not-in-list
 *  [] clock
 *
 * message
 *  [] show smiles
 *  [] history
 *  [] composing
 *
 * startup actions
 *  [] login
 *  [] Join conferences
 *
 * application
 *  [] fullscreen
 */

public class ConfigForm implements
	CommandListener 
//#if !(MIDP1)
	,ItemCommandListener
//#endif
	//,ItemStateListener
{
    private Display display;
    private Displayable parentView;

    Form f;
    ChoiceGroup roster;
    //ChoiceGroup nil; <voffk>
    ChoiceGroup message;
    NumberField MessageLimit;
    ChoiceGroup startup;
    ChoiceGroup application;

    //<voffk>
//#if !(ReleaseZLITE)
    ChoiceGroup lang;
//#endif    
//#if ARCHIVE_ADVANCED
    ChoiceGroup archive;
    boolean arch[];
//#endif
    
    ChoiceGroup sndFile;
    
    Gauge sndVol;
    NumberField maxreconnect;
    //</voffk>
    
    ChoiceGroup font1;
    ChoiceGroup font2;
    
    ChoiceGroup textWrap;
    
    ChoiceGroup autoAwayType;
    
    //NumberField keepAlive;
    NumberField fieldLoc;
    NumberField fieldGmt;
    
    NumberField fieldAwatDelay;
    
//#if COLOR_THEMES
    ChoiceGroup themeFile;
    Vector themeFiles[];
//#endif
    
    Command cmdOk=new Command(SR.MS_OK,Command.OK,1);
    //Command cmdSign=new Command("- (Sign)",Command.ITEM,2);
    Command cmdPlaySound=new Command(SR.MS_TEST_SOUND, Command.ITEM,10);
    Command cmdCancel=new Command(SR.MS_CANCEL, Command.BACK,99);
    
    Config cf;
    boolean ra[];
    boolean mv[];
    boolean ap[];
    boolean su[];
    Vector files[];
//#if !(ReleaseZLITE)
    Vector langs[];
//#endif
    
    /** Creates a new instance of ConfigForm */
    public ConfigForm(Display display) {
        this.display=display;
        parentView=display.getCurrent();
        
        cf=Config.getInstance();
        
        f=new Form(SR.MS_OPTIONS);
        roster=new ChoiceGroup(SR.MS_ROSTER_ELEMENTS, Choice.MULTIPLE);
        roster.append(SR.MS_OFFLINE_CONTACTS, null);
//#if !ReleaseZVOFFK
        roster.append("self-contacts", null);
        roster.append(SR.MS_TRANSPORTS, null);
//#endif
        roster.append(SR.MS_IGNORE_LIST, null);
//#if !ReleaseZVOFFK
        roster.append("Not-in-list presences", null);
//#endif
        roster.append(SR.MS_AUTOFOCUS,null);
        roster.append(SR.MS_AUTH_NEW,null);
        roster.append(SR.MS_LAST_APPEARED_CONTACTS, null);
        
        boolean ra[]={
            cf.showOfflineContacts,
//#if !ReleaseZVOFFK
            cf.selfContact, 
            cf.showTransports,
//#endif
            cf.ignore, 
//#if !ReleaseZVOFFK
            cf.notInListPresences,
//#endif
            cf.autoFocus,
            cf.autoSubscribe,
            cf.lastAppearedContacts //<voffk>
        };
        this.ra=ra;
        //ra[5]=false;
        roster.setSelectedFlags(ra);
 
        /*nil=new ChoiceGroup(SR.MS_NOT_IN_LIST, ConstMIDP.CHOICE_POPUP);
        nil.append(SR.MS_NIL_DROP_MP, null);
        nil.append(SR.MS_NIL_DROP_P, null);
        nil.append(SR.MS_NIL_ALLOW_ALL, null);
        nil.setSelectedIndex((cf.notInListDropLevel>NotInListFilter.ALLOW_ALL)? NotInListFilter.ALLOW_ALL: cf.notInListDropLevel, true); */ //<voffk>
        
        message=new ChoiceGroup(SR.MS_MESSAGES, Choice.MULTIPLE);
        message.append(SR.MS_SMILES, null);
//#if (HISTORY)        
//#         message.append(SR.MS_HISTORY, null);
//#endif
        message.append(SR.MS_STORE_PRESENCE,null);        
        message.append(SR.MS_COMPOSING_EVENTS, null);
        message.append(SR.MS_DELIVERY, null);
        message.append(SR.MS_CAPS_STATE, null);
 //<voffk>
        //message.append(SR.MS_PEP, null);
        message.append(SR.MS_EMULATE_TABS, null);
        message.append(SR.MS_CONFIRM_DELETE_MESSAGES, null);
        message.append(SR.MS_AUTOSCROLL, null);
//#if CLIPBOARD
//#         message.append(SR.MS_CLIPBOARD, null);
//#endif
//#if PEP
        message.append(SR.MS_MOOD, null);
 //#if PEP_TUNE
        message.append(SR.MS_TUNE, null);
 //#endif
//#endif
 //</voffk>
        
        boolean mv[]={
            cf.smiles,
//#if (HISTORY)        
//#             cf.msgLog,
//#endif
            cf.storeConfPresence,
            cf.eventComposing,
            cf.eventDelivery,
            cf.capsState,
            //<voffk>
            cf.useTabs,
            cf.confirmDelete,
            cf.autoScroll,
//#if CLIPBOARD
//#             cf.useClipBoard,
//#endif
//#if PEP
            cf.enableMood,
 //#if PEP_TUNE
            cf.enableTune
 //#endif
//#endif
            //</voffk>
        };
        this.mv=mv;
        
        message.setSelectedFlags(mv);
        
        MessageLimit=new NumberField(SR.MS_MESSAGE_COLLAPSE_LIMIT, cf.messageCollapsedLength, 50, 1000);
        
	startup=new ChoiceGroup(SR.MS_STARTUP_ACTIONS, Choice.MULTIPLE);
        startup.append(SR.MS_AUTOLOGIN, null);
        startup.append(SR.MS_AUTO_CONFERENCES,null);
        //<voffk>
        startup.append(SR.MS_ACCOUNT_SELECT, null);
        su=new boolean[3];
        su[0]=cf.autoLogin;
        su[1]=cf.autoJoinConferences;
        su[2]=cf.accountSelect;
        //</voffk>
        startup.setSelectedFlags(su);

        ap=new boolean[7];
	int apctr=0;
        application=new ChoiceGroup(SR.MS_APPLICATION, Choice.MULTIPLE);
        application.append(SR.MS_FULLSCREEN,null);
        ap[apctr++]=cf.fullscreen;
        application.append(SR.MS_HEAP_MONITOR,null);
        ap[apctr++]=cf.memMonitor;
        application.append(SR.MS_SHOW_HARDWARE,null);
        ap[apctr++]=cf.enableVersionOs;
	if (!cf.ghostMotor) {
            ap[apctr++]=cf.blFlash;
            application.append(SR.MS_FLASHBACKLIGHT,null);
        }
//#if LIGHT_CONTROL
//#         ap[apctr++]=cf.lightState;
//#         application.append("turn on light (SIE, SE & Nokia)", null);
//#endif
        if (cf.allowMinimize) {
            ap[apctr++]=cf.popupFromMinimized;
	    application.append(SR.MS_ENABLE_POPUP,null);
        }
//#if TRAFFIC
//#         //<voffk>
//#         ap[apctr++]=cf.counterTraffic;
//#         application.append(SR.MS_TRAFFIC_COUNTER, null);
//#endif
        
        application.setSelectedFlags(ap);
        
        autoAwayType=new ChoiceGroup(SR.MS_AWAY_TYPE, ChoiceGroup.POPUP); //<voffk>
        autoAwayType.append(SR.MS_AWAY_OFF, null);
        autoAwayType.append(SR.MS_AWAY_LOCK, null);
        autoAwayType.append(SR.MS_AWAY_IDLE, null);
        autoAwayType.setSelectedIndex(cf.autoAwayType, true);
        fieldAwatDelay=new NumberField(SR.MS_AWAY_PERIOD, cf.autoAwayDelay, 1, 30);
        
        
	// keepAlive=new NumberField(SR.MS_KEEPALIVE_PERIOD, cf.keepAlive, 20, 600 );
	fieldGmt=new NumberField(SR.MS_GMT_OFFSET, cf.gmtOffset, -12, 12); 
        fieldLoc=new NumberField(SR.MS_CLOCK_OFFSET, cf.locOffset, -12, 12 );
        
        sndFile=new ChoiceGroup(SR.MS_SOUND, ChoiceGroup.POPUP); //<voffk>
        
        //<voffk>
        sndVol=new Gauge(SR.MS_SOUND_VOLUME, true, 10,  cf.soundVol/10);
//#if ARCHIVE_ADVANCED
        archive=new ChoiceGroup(SR.MS_ARCHIVE, Choice.MULTIPLE);
        archive.append("export to cp1251", null);
        arch=new boolean[1];
        arch[0]=cf.cp1251;
        archive.setSelectedFlags(arch);
//#endif
        maxreconnect=new NumberField(SR.MS_MAX_RECONNECT, cf.maxReconnect, 0, 30);
        //<voffk>
	
        files=new StringLoader().stringLoader("/sounds/res.txt",3);
	
	for (Enumeration f=files[2].elements(); f.hasMoreElements(); ) {
	    sndFile.append( (String)f.nextElement(), null );
	}
	
        try {
            sndFile.setSelectedIndex(cf.soundsMsgIndex, true);
        } catch (Exception e) { cf.soundsMsgIndex=0; };

//#if COLOR_THEMES
        themeFile=new ChoiceGroup(SR.MS_COLOR_THEME, ChoiceGroup.POPUP); //<voffk>
        themeFiles=new StringLoader().stringLoader("/themes/res.txt",2);
        for (Enumeration f=themeFiles[1].elements(); f.hasMoreElements(); ) {
            themeFile.append( (String)f.nextElement(), null );
        }
        try {
            themeFile.setSelectedIndex(cf.colorTheme, true);
        } catch (Exception e) { cf.colorTheme=0; };
//#endif
        
        String fnts[]={SR.MS_FONTSIZE_NORMAL, SR.MS_FONTSIZE_SMALL, SR.MS_FONTSIZE_LARGE};
        font1=new ChoiceGroup(SR.MS_ROSTER_FONT, ChoiceGroup.POPUP, fnts, null); //<voffk>
        font2=new ChoiceGroup(SR.MS_MESSAGE_FONT, ChoiceGroup.POPUP, fnts, null); //<voffk>
        font1.setSelectedIndex(cf.font1/8, true);
        font2.setSelectedIndex(cf.font2/8, true);

//#if COLOR_THEMES
        f.append(themeFile);
//#endif      
        f.append(sndFile); //<voffk>
	f.append(sndVol); //<voffk>
        
        f.append(roster);
        //f.append(nil); <voffk>
        f.append(font1);
        f.append(font2); //<voffk>

        f.append(message);
        f.append(MessageLimit);
        //f.append(font2); <voffk>
	
	String textWraps[]={SR.MS_TEXTWRAP_CHARACTER, SR.MS_TEXTWRAP_WORD};
	textWrap=new ChoiceGroup(SR.MS_TEXTWRAP, ChoiceGroup.POPUP, textWraps,null); //<voffk>
	textWrap.setSelectedIndex(cf.textWrap, true);
	f.append(textWrap);
	
        //<voffk>
	//f.append(sndFile);
 	
///#if COLOR_THEMES
//        f.append(themeFile);
///#endif
       
//#if !(ReleaseZLITE)
        lang=new ChoiceGroup("Language", ChoiceGroup.POPUP); //<voffk>
        langs=new StringLoader().stringLoader("/lang/res.txt",3);
	
	for (int i=0; i<langs[0].size(); i++) {
            String label=(String) langs[2].elementAt(i);
            String langCode=(String) langs[0].elementAt(i);
	    lang.append( label, null );
            if (cf.lang.equals(langCode))
                lang.setSelectedIndex(i, true);
	}
//#endif
        
        //sndVol=new Gauge("Sound volume", true, 10,  cf.soundVol/10);
	//f.append(sndVol);
        
	sndFile.addCommand(cmdPlaySound);
	sndFile.setItemCommandListener(this);
        
	sndVol.addCommand(cmdPlaySound);
	sndVol.setItemCommandListener(this);
	//</voffk>
//#if ARCHIVE_ADVANCED
        f.append(archive); //<voffk>
//#endif
	f.append(startup);

	f.append(application);
        
        f.append(maxreconnect); //<voffk>
        
        f.append(autoAwayType);
        f.append(fieldAwatDelay);
	//f.append(keepAlive);
	
        /*f.append(SR.MS_TIME_SETTINGS);
        f.append("\n");*/
        
        f.append(fieldGmt);
        f.append(fieldLoc);
        
//#if !(ReleaseZLITE)
        f.append(lang);
//#endif   

        f.addCommand(cmdOk);
        f.addCommand(cmdCancel);
        
        f.setCommandListener(this);
	//f.setItemStateListener(this);
        
        display.setCurrent(f);
    }
    
    public void commandAction(Command c, Displayable d) {
        if (c==cmdOk) {
            roster.getSelectedFlags(ra);
            message.getSelectedFlags(mv);
            application.getSelectedFlags(ap);
	    startup.getSelectedFlags(su);

            //cf.notInListDropLevel=nil.getSelectedIndex(); <voffk>
            int raIdx=0;
            cf.showOfflineContacts=ra[raIdx++];
            /*cf.selfContact=ra[1];
            cf.showTransports=ra[2];*/ //<voffk>
//#if !ReleaseZVOFFK
            cf.selfContact=ra[raIdx++];
            cf.showTransports=ra[raIdx++];
//#endif
            cf.ignore=ra[raIdx++];
//#if !ReleaseZVOFFK
            cf.notInListPresences=ra[raIdx++];
//#endif
            cf.autoFocus=ra[raIdx++];
            cf.autoSubscribe=ra[raIdx++];
            cf.lastAppearedContacts=ra[raIdx++]; //<voffk>

            cf.smiles=mv[0];
            int haIdx=1;
//#if (HISTORY)
//#             cf.msgLog=mv[1];
//#             haIdx=2;
//#endif
            cf.storeConfPresence=mv[haIdx++];
            cf.eventComposing=mv[haIdx++];
            cf.eventDelivery=mv[haIdx++];
            cf.capsState=mv[haIdx++];
            //<voffk>
            cf.useTabs=mv[haIdx++];
            cf.confirmDelete=mv[haIdx++];
            cf.autoScroll=mv[haIdx++];
//#if CLIPBOARD
//#             cf.useClipBoard=mv[haIdx++];
//#endif
//#if PEP
            cf.enableMood=mv[haIdx++];
 //#if PEP_TUNE
            cf.enableTune=mv[haIdx++];
 //#endif
//#endif
	    
	    cf.autoLogin=su[0];
	    cf.autoJoinConferences=su[1];
            cf.accountSelect=su[2];
            //</voffk>
            
	    int apctr=0;
            VirtualList.fullscreen=cf.fullscreen=ap[apctr++];
            StaticData.getInstance().roster.setFullScreenMode(cf.fullscreen);
	    VirtualList.memMonitor=cf.memMonitor=ap[apctr++];
            cf.enableVersionOs=ap[apctr++];
	    if (!cf.ghostMotor)
                cf.blFlash=ap[apctr++];
//#if LIGHT_CONTROL
//#             cf.lightState=ap[apctr++];
//#endif
	    if (cf.allowMinimize)
                cf.popupFromMinimized=ap[apctr++];
//#if TRAFFIC
//#             cf.counterTraffic=ap[apctr++]; //<voffk>
//#endif
            
	    cf.gmtOffset=fieldGmt.getValue();
	    cf.locOffset=fieldLoc.getValue();
	    //cf.keepAlive=keepAlive.getValue();
	    
//#if COLOR_THEMES
            cf.colorTheme=themeFile.getSelectedIndex();
            ui.Colors.initColors();
//#endif
                
	    cf.soundsMsgIndex=sndFile.getSelectedIndex();
            
            FontCache.rosterFontSize=cf.font1=font1.getSelectedIndex()*8;
            FontCache.msgFontSize=cf.font2=font2.getSelectedIndex()*8;
            FontCache.resetCache();
	    
	    cf.textWrap=textWrap.getSelectedIndex();
	    
            //<voffk>
	    cf.soundVol=sndVol.getValue()*10;
//#if ARCHIVE_ADVANCED
            archive.getSelectedFlags(arch);
            cf.cp1251=arch[0];
//#endif
            cf.maxReconnect=maxreconnect.getValue();
//#if !(ReleaseZLITE)
            cf.lang=(String) langs[0].elementAt( lang.getSelectedIndex() );         
//#else
//#             cf.lang="ru";
//#endif
            //</voffk>
            cf.autoAwayDelay=fieldAwatDelay.getValue();
            cf.autoAwayType=autoAwayType.getSelectedIndex();
            
            cf.loadSoundName();
            
            cf.messageCollapsedLength=MessageLimit.getValue();
//#if LIGHT_CONTROL
//#             StaticData.getInstance().roster.setLight(cf.lightState);
//#endif
            cf.updateTime();
            
            cf.saveToStorage();
            
            //<voffk>
            if (StaticData.getInstance().roster.isLoggedIn()) {
                String oldVerHash=EntityCaps.calcVerHash();
                
                EntityCaps.initCaps();
            
                if (!oldVerHash.equals(EntityCaps.calcVerHash()))
                    StaticData.getInstance().roster.sendPresence(Presence.PRESENCE_SAME, null);
            }
            //</voffk>
            
            StaticData.getInstance().roster.reEnumRoster();
            destroyView();
        }
        if (c==cmdCancel) destroyView();
    }

    public void commandAction(Command command, Item item) {
	if (command==cmdPlaySound) {
	    testSound();
	}
    }
    
    public void destroyView(){
        if (display!=null)   display.setCurrent(parentView);
        ((Canvas)parentView).setFullScreenMode(cf.fullscreen);
    }

    /*public void itemStateChanged(Item item) {
	if (item==sndVol || item==soundFile) 
     */
    private void testSound(){
	int sound=sndFile.getSelectedIndex();
	String soundFile=(String)files[1].elementAt(sound);
	String soundType=(String)files[0].elementAt(sound);
        //<voffk>
        int soundVol=sndVol.getValue()*10;
        new EventNotify(display, soundType, soundFile, soundVol, 0, false).startNotify();
        //</voffk>
    }

}
